package pl.wroc.uni.ii.puzzle.game;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;

public class Cell {

	private boolean isSelected;
	private ImageFragment imageFragment;
	private Rect selectionCircuitPosition;
	private Rect positionOnBoard;
	
	public Cell(int row, int column, int width, int height, Bitmap image) {
		isSelected = false;

		positionOnBoard = new Rect();
		int left = width * column;
		int top = height * row;
		int right = left + width;
		int bottom = top + height;
		positionOnBoard.set(left, top, right, bottom);
		selectionCircuitPosition = new Rect(left+1, top+1, right-1, bottom-1);
		
		Bitmap cellImage = Bitmap.createBitmap(image, left, top, width, height);
		imageFragment = new ImageFragment(cellImage, positionOnBoard);
	}

	public void draw(Canvas canvas) {		
		Paint paint = new Paint();

		canvas.drawBitmap(imageFragment.getCellImage(), positionOnBoard.left, positionOnBoard.top, paint);
		if (isSelected) {
			drawSelectionCircuit(canvas, paint);
		}
	}
	
	private void drawSelectionCircuit(Canvas canvas, Paint paint) {
		paint.setColor(Color.RED);
		paint.setStyle(Style.STROKE);
		paint.setStrokeWidth(2);
		canvas.drawRect(selectionCircuitPosition, paint);
	}

	public void switchSelection() {
		isSelected = !isSelected;
	}
	
	public boolean isInProperPosition() {
		return imageFragment.isInProperPosition(positionOnBoard);
	}
	
	public boolean isSelected() {
		return isSelected;
	}
	
	public void swapPostionWithCell(Cell c) {
		ImageFragment imageFragmentFromC = c.getImageFragment();
		c.setImageFragment(this.imageFragment);
		this.imageFragment = imageFragmentFromC;
	}
	
	public void reflectHorizontal() {
		imageFragment.reflectHorizontal();
	}

	public void reflectVertical() {
		imageFragment.reflectVertical();
	}

	public ImageFragment getImageFragment() {
		return imageFragment;
	}

	public void setImageFragment(ImageFragment imageFragment) {
		this.imageFragment = imageFragment;
	}
}
